<template>
  <view class="container">
    <!-- 顶部用户信息 -->
<!--   <view class="user-info-box">
      <view class="user-info" v-if="isLogin">
        <u-avatar :src="userInfo.avatar || '/static/images/default-avatar.jpg'" size="120"></u-avatar>
        <view class="user-name">{{ userInfo.nickname || '未设置昵称' }}</view>
      </view>
      <view class="user-info" v-else @click="goLogin">
        <u-avatar size="120"></u-avatar>
        <view class="user-name">点击登录</view>
      </view>
    </view> -->
    
    <!-- 数据概览 -->
    <view class="overview-section">
      <view class="overview-title">
        <text>数据概览</text>
        <u-icon name="arrow-right" color="#999" size="28"></u-icon>
      </view>
      <view class="overview-cards">
        <view class="overview-card" @click="navTo('/pages/todo/index')">
          <view class="card-count">{{ todoCount }}</view>
          <view class="card-title">待办事项</view>
          <view class="card-progress">
            <u-line-progress :percentage="todoProgress" :showText="false" height="8" activeColor="#2979ff"></u-line-progress>
          </view>
          <view class="card-desc">完成进度 {{ todoProgress }}%</view>
        </view>
        <view class="overview-card" @click="navTo('/pages/wish/index')">
          <view class="card-count">{{ wishCount }}</view>
          <view class="card-title">愿望清单</view>
          <view class="card-progress">
            <u-line-progress :percentage="wishProgress" :showText="false" height="8" activeColor="#19be6b"></u-line-progress>
          </view>
          <view class="card-desc">实现进度 {{ wishProgress }}%</view>
        </view>
        <view class="overview-card" @click="navTo('/pages/achievement/index')">
          <view class="card-count">{{ achievementCount }}</view>
          <view class="card-title">成果记录</view>
          <view class="card-desc">本月新增 {{ newAchievementCount }}</view>
        </view>
      </view>
    </view>
    
    <!-- 待办事项列表 -->
    <view class="todo-section">
      <view class="section-header">
        <text class="section-title">待办事项</text>
        <text class="section-more" @click="navTo('/pages/todo/index')">查看更多</text>
      </view>
      <view class="todo-list">
        <view v-if="todoList.length === 0" class="empty-tip">
          <u-empty mode="list" icon="/static/images/empty-list.png" text="暂无待办事项"></u-empty>
        </view>
        <view v-else class="todo-item" v-for="(item, index) in todoList" :key="index" @click="navTo(`/pages/todo/detail?id=${item.id}`)">
          <view class="todo-item-left">
            <view class="custom-checkbox" @click.stop="handleTodoCheck(item)">
              <view class="checkbox-inner" :class="{'checkbox-checked': item.status === 2}"></view>
            </view>
          </view>
          <view class="todo-item-content">
            <view class="todo-item-title" :class="{'todo-completed': item.status === 2}">{{ item.title }}</view>
            <view class="todo-item-info">
              <u-tag v-if="item.status === 0" text="待办" type="warning" size="mini"></u-tag>
              <u-tag v-else-if="item.status === 1" text="进行中" type="primary" size="mini"></u-tag>
              <u-tag v-else text="已完成" type="success" size="mini"></u-tag>
              <text class="todo-deadline" v-if="item.deadline">截止: {{ formatDate(item.deadline) }}</text>
            </view>
          </view>
          <view class="todo-item-right" @click.stop="handleStatusChange(item)">
            <u-icon v-if="item.status === 0" name="play-right" color="#909399" size="30"></u-icon>
            <u-icon v-else-if="item.status === 1" name="clock" color="#2979ff" size="30"></u-icon>
            <u-icon v-else name="checkmark" color="#19be6b" size="30"></u-icon>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 愿望清单列表 -->
    <view class="wish-section">
      <view class="section-header">
        <text class="section-title">愿望清单</text>
        <text class="section-more" @click="navTo('/pages/wish/index')">查看更多</text>
      </view>
      <view class="wish-list">
        <view v-if="wishList.length === 0" class="empty-tip">
          <u-empty mode="list" icon="/static/images/empty-list.png" text="暂无愿望清单"></u-empty>
        </view>
        <view v-else class="wish-item" v-for="(item, index) in wishList" :key="index" @click="navTo(`/pages/wish/detail?id=${item.id}`)">
          <view class="wish-item-content">
            <view class="wish-item-title">{{ item.title }}</view>
            <view class="wish-item-progress">
              <u-line-progress :percentage="item.progress" :showText="true" height="12" activeColor="#19be6b"></u-line-progress>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 添加按钮 -->
    <view class="add-btn-container">
      <u-button type="primary" shape="circle" icon="plus" @click="showAddActionSheet"></u-button>
    </view>
    
    <!-- 添加操作菜单 -->
    <u-action-sheet :list="actionSheetList" v-model="showActionSheet" @click="handleActionSheetClick"></u-action-sheet>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
import { getOverview, getHomeList } from '@/api/home'

export default {
  data() {
    return {
      todoList: [],
      wishList: [],
      todoCount: 0,
      todoProgress: 0,
      wishCount: 0,
      wishProgress: 0,
      achievementCount: 0,
      newAchievementCount: 0,
      showActionSheet: false,
      actionSheetList: [
        { text: '添加待办事项', icon: 'calendar-fill', color: '#2979ff' },
        { text: '添加愿望', icon: 'star-fill', color: '#ff9900' },
        { text: '记录成果', icon: 'checkmark-circle-fill', color: '#19be6b' }
      ]
    }
  },
  computed: {
    ...mapGetters({
      isLogin: 'user/isLogin',
      userInfo: 'user/userInfo'
    })
  },
  onLoad() {
    this.loadData()
  },
  onShow() {
    // 页面显示时刷新数据
    this.loadData()
  },
  onPullDownRefresh() {
    this.loadData()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 1000)
  },
  methods: {
    // 加载首页数据
    async loadData() {
      if (!this.isLogin) {
        return
      }
      
      try {
        // 显示加载中
        uni.showLoading({
          title: '加载中...'
        })
        
        // 获取首页概览数据
        const overviewResponse = await getOverview()
        console.log('概览数据原始响应:', overviewResponse)
        
        // 处理概览数据 - 考虑两种可能的响应格式
        const overviewData = overviewResponse.data || overviewResponse
        console.log('处理后的概览数据:', overviewData)
        
        if (overviewData) {
          // 如果存在todo、wish、achievement字段
          if (overviewData.todo && overviewData.wish && overviewData.achievement) {
            const { todo, wish, achievement } = overviewData
            // 转换字符串为数字
            this.todoCount = parseInt(todo.count) || 0
            this.todoProgress = parseInt(todo.progress) || 0
            this.wishCount = parseInt(wish.count) || 0
            this.wishProgress = parseInt(wish.progress) || 0
            this.achievementCount = parseInt(achievement.count) || 0
            this.newAchievementCount = parseInt(achievement.newCount) || 0
            
            console.log('概览数据处理成功')
          } else {
            console.error('概览数据格式不正确')
            this.resetOverviewData()
          }
        } else {
          console.error('获取概览数据失败')
          this.resetOverviewData()
        }
        
        // 获取首页列表数据
        const listResponse = await getHomeList()
        console.log('列表数据原始响应:', listResponse)
        
        // 处理列表数据 - 考虑两种可能的响应格式
        const listData = listResponse.data || listResponse
        console.log('处理后的列表数据:', listData)
        
        if (listData) {
          // 处理todoList
          if (Array.isArray(listData.todoList)) {
            this.todoList = listData.todoList.map(item => {
              return {
                ...item,
                checked: item.status === 2,
                title: item.title || ''
              };
            });
            console.log('todoList处理成功:', this.todoList.length);
          } else {
            console.error('todoList格式不正确');
            this.todoList = [];
          }
          
          // 处理wishList
          if (Array.isArray(listData.wishList)) {
            this.wishList = listData.wishList.map(item => ({
              ...item,
              progress: parseInt(item.progress) || 0,
              title: item.title || ''
            }))
            console.log('wishList处理成功:', this.wishList.length)
          } else {
            console.error('wishList格式不正确')
            this.wishList = []
          }
        } else {
          console.error('获取列表数据失败')
          this.resetListData()
        }
      } catch (error) {
        console.error('加载首页数据失败', error)
        this.resetAllData()
        uni.showToast({
          icon: 'none',
          title: '加载数据失败，请重试'
        })
      } finally {
        // 隐藏加载中
        uni.hideLoading()
      }
    },
    
    // 重置概览数据
    resetOverviewData() {
      this.todoCount = 0
      this.todoProgress = 0
      this.wishCount = 0
      this.wishProgress = 0
      this.achievementCount = 0
      this.newAchievementCount = 0
    },
    
    // 重置列表数据
    resetListData() {
      this.todoList = []
      this.wishList = []
    },
    
    // 重置所有数据
    resetAllData() {
      this.resetOverviewData()
      this.resetListData()
    },
    
    // 处理待办事项勾选
    async handleTodoCheck(item) {
      // 点击复选框只处理完成/未完成两种状态
      const newChecked = !item.checked;
      const newStatus = newChecked ? 2 : item.status === 0 ? 0 : 1; // 如果原来是待办，取消勾选后仍然是待办
      
      try {
        // 更新UI
        item.checked = newChecked;
        item.status = newStatus;
        
        // 发送请求到后端
        const result = await this.$store.dispatch('todo/updateTodo', {
          id: item.id,
          status: newStatus
        });
        
        // 简单记录响应但不做复杂判断
        //console.log('更新待办状态响应:', result);
        
        // 刷新数据
        this.loadData();
        
        // 提示用户更新成功
        uni.showToast({
          title: '更新成功',
          icon: 'success'
        });
      } catch (error) {
        //console.error('更新待办状态失败', error);
        // 发生错误时提示用户
        // uni.showToast({
        //   title: '更新失败',
        //   icon: 'none'
        // });
      }
    },
    
    // 添加新方法：处理状态循环切换
    async handleStatusChange(item) {
      // 状态循环：0(待办) -> 1(进行中) -> 2(已完成) -> 0(待办)
      const originalStatus = item.status;
      const newStatus = (item.status + 1) % 3;
      const newChecked = newStatus === 2; // 只有状态为2(已完成)时才勾选
      
      try {
        // 更新UI
        item.status = newStatus;
        item.checked = newChecked;
        
        // 发送请求到后端
        const result = await this.$store.dispatch('todo/updateTodo', {
          id: item.id,
          status: newStatus
        });
        
        // 简单记录响应但不做复杂判断
        console.log('更新待办状态响应:', result);
        
        // 提示用户
        const statusText = ['待办', '进行中', '已完成'][newStatus];
        uni.showToast({
          title: `已更新为${statusText}`,
          icon: 'success'
        });
        
        // 刷新数据
        this.loadData();
      } catch (error) {
        //console.error('更新待办状态失败', error);
        // 发生错误时提示用户并回滚UI
        // item.status = originalStatus;
        // item.checked = originalStatus === 2;
        
          // uni.showToast({
          //   title: '更新失败',
          //   icon: 'none'
          // });
      }
    },
    
    // 显示添加操作菜单
    showAddActionSheet() {
      this.showActionSheet = true
    },
    
    // 处理操作菜单点击
    handleActionSheetClick(index) {
      switch (index) {
        case 0:
          this.navTo('/pages/todo/edit')
          break
        case 1:
          this.navTo('/pages/wish/edit')
          break
        case 2:
          this.navTo('/pages/achievement/edit')
          break
      }
    },
    
    // 页面导航
    navTo(url) {
      console.log('尝试跳转到:', url)
      
      // 检查登录状态
      if (!this.isLogin && url !== '/pages/user/login') {
        console.log('用户未登录，重定向到登录页面')
        this.goLogin()
        return
      }
      
      try {
        uni.navigateTo({ 
          url,
          success: () => {
            console.log('跳转成功:', url)
          },
          fail: (err) => {
            console.error('跳转失败:', err)
            // 尝试使用 switchTab 跳转（如果是 tabBar 页面）
            uni.switchTab({
              url,
              fail: (switchErr) => {
                console.error('switchTab 也失败了:', switchErr)
              }
            })
          }
        })
      } catch (error) {
        console.error('跳转异常:', error)
      }
    },
    
    // 去登录
    goLogin() {
      uni.navigateTo({
        url: '/pages/user/login'
      })
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      
      try {
        // 处理日期格式，确保兼容iOS
        // 将yyyy-MM-dd HH:mm:ss格式转换为yyyy/MM/dd HH:mm:ss
        const formattedDateStr = dateStr.replace(/-/g, '/');
        const date = new Date(formattedDateStr);
        
        if (isNaN(date.getTime())) return '';
        
        return `${date.getMonth() + 1}月${date.getDate()}日`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return '';
      }
    },
    
    // 获取进度条颜色的方法
    getProgressColor(status) {
      switch (status) {
        case 0: return '#909399'; // 待办：灰色
        case 1: return '#2979ff'; // 进行中：蓝色
        case 2: return '#19be6b'; // 已完成：绿色
        default: return '#909399';
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 120rpx;
}

.user-info-box {
  background-color: #2979ff;
  padding: 40rpx 30rpx;
  border-bottom-left-radius: 40rpx;
  border-bottom-right-radius: 40rpx;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user-name {
  margin-top: 20rpx;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
}

.overview-section {
  margin: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.overview-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
  margin-bottom: 20rpx;
  font-size: 30rpx;
  font-weight: 500;
}

.overview-cards {
  display: flex;
  justify-content: space-between;
}

.overview-card {
  flex: 1;
  padding: 20rpx;
  text-align: center;
  border-right: 1px solid #f5f5f5;
}

.overview-card:last-child {
  border-right: none;
}

.card-count {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.card-title {
  font-size: 24rpx;
  color: #666;
  margin: 10rpx 0;
}

.card-progress {
  margin: 10rpx 0;
}

.card-desc {
  font-size: 22rpx;
  color: #999;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 500;
}

.section-more {
  font-size: 24rpx;
  color: #2979ff;
}

.todo-section, .wish-section {
  background-color: #fff;
  margin: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.todo-list, .wish-list {
  padding: 0 30rpx 30rpx;
}

.empty-tip {
  padding: 40rpx 0;
}

.todo-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.todo-item:last-child {
  border-bottom: none;
}

.todo-item-left {
  margin-right: 20rpx;
}

.todo-item-content {
  flex: 1;
}

.todo-item-title {
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.todo-completed {
  text-decoration: line-through;
  color: #999;
}

.todo-item-info {
  display: flex;
  align-items: center;
}

.todo-deadline {
  margin-left: 10rpx;
  font-size: 22rpx;
  color: #999;
}

.todo-item-right {
  margin-left: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
}

.wish-item {
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.wish-item:last-child {
  border-bottom: none;
}

.wish-item-title {
  font-size: 28rpx;
  margin-bottom: 16rpx;
}

.wish-item-progress {
  margin-top: 10rpx;
}

.add-btn-container {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  z-index: 9;
}

// 自定义复选框样式
.custom-checkbox {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  
  .checkbox-inner {
    width: 24rpx;
    height: 24rpx;
    border-radius: 50%;
    background-color: transparent;
    transition: all 0.2s;
  }
  
  .checkbox-checked {
    background-color: #19be6b;
  }
}
</style> 